﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;

using Ext.Net;
using BG.Data;
using BG.Service;
using Kwan.Helper.Bitmaps;
using Kwan.Data;
using Kwan.Helper.Xmls;

namespace BG.Web.Admin.Order
{
    public partial class Default : UIPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                //BtnAddClassInfo.Hidden = !permit[0];
                //AppendChild.Hidden = !permit[0];
                //BtnAddInfo.Hidden = !permit[0];
                //Rename.Hidden = !permit[2];
                //btnChangeHot.Hidden = !permit[2];

                //BtnDeleteInfo.Hidden = !permit[3];
                //Remove.Hidden = !permit[3];
                //if (permit[3])
                //{
                //    List<GridCommand> gridCommand = new List<GridCommand>{
                //        ExtHelper.CreateGridCommand("Delete", Icon.Delete, "禁用", "将该记录禁用")
                //    };
                //    GridPanel1.ColumnModel.Columns.Add(ExtHelper.CreateCommandColumn(gridCommand));
                //}
                ResourceManager1.RegisterIcon(Icon.RecordBlue);
                ResourceManager1.RegisterIcon(Icon.RecordGreen);
                ResourceManager1.RegisterIcon(Icon.RecordRed);
                ResourceManager1.RegisterIcon(Icon.BulletCross);
            }
        }

        protected void BtnAddInfo_Click(object sender, EventArgs e)
        {
            SetEditWindow(new VOrder() { Status = 2, Days = 1 });
            EditWindow.Show();
        }

        [DirectMethod]
        public void DeleteSelected(string obj)
        {
            string[] list = obj.Split(',');
            using (IConnectinContext cc = DBContext.Context1)
            {
                for (int i = 0; i < list.Length - 1; i++)
                {
                    TOrder t = (TOrder.entityID == list[i]).ListFirst<TOrder>();
                    t.Status = 0;
                    DBContext.Save(t);
                    (TRoom.entityID == t.RoomID).Edit<TRoom>(d => { d.Status = 1; });
                }
            }
            Store1.DataBind();
        }

        [DirectMethod]
        public void ChangeState(string obj, string NameValue)
        {
            IList<TOrder> list = JSON.Deserialize<IList<TOrder>>(obj);
            if (list.Count > 0)
            {
                foreach (TOrder tt in list)
                {
                    string[] arr = NameValue.Split(char.Parse("_"));
                    int status = Convert.ToInt32(arr[1]);
                    (TOrder.entityID == tt.EntityID).Edit<TOrder>(p => p.Status = status);
                    switch (status)
                    {
                        case 0:
                        case 1:
                        case 2:
                            (TRoom.entityID == tt.RoomID).Edit<TRoom>(d => { d.Status = status; }); break;
                        case 3:
                            (TRoom.entityID == tt.RoomID).Edit<TRoom>(d => { d.Status = 1; }); break;
                    }
                }
                //CrudManage.ChangeState(list, NameValue);
                Store1.DataBind();
            }
            else
            {
                ExtHelper.GetNotification("系统提示", "请至少选择一项！").Show();
            }
        }

        [DirectMethod]
        public void EditInfo(string EntityID)
        {
            if (!permit[2]) return;
            SetEditWindow((TOrder.entityID == int.Parse(EntityID)).ListFirst<VOrder>());
            EditWindow.Show();
        }

        protected void RefreshDS(object sender, StoreRefreshDataEventArgs e)
        {
            NameValueCollection ps = new NameValueCollection();
            ps.Set("gridsort", e.Sort);
            ps.Set("dir", e.Dir.ToString());
            
            //搜索项
            ps.Set("Cid", txtFilter.Text);
            ps.Set("tag", txtSearch.Text);

            int pageindex = e.Start / e.Limit;
            Kwan.Data.Region r = new Kwan.Data.Region(pageindex, e.Limit);

            Expression exp = OrderQuery.MakeSearchWhere(ps);
            IList<VOrder> ListView = exp.List<VOrder>(r, new string[] { e.Sort + " " + e.Dir });

            e.Total = exp.Count<TOrder>();
            Store1.DataSource = ListView;
            Store1.DataBind();
        }

        [DirectMethod]
        public void SetFormChange(int roomID)
        {
            TUser u = (TUser.userName == Page.User.Identity.Name).ListFirst<TUser>();

            VRoom room = (TRoom.entityID == roomID).ListFirst<VRoom>();
            if (room == null)
            {
                ExtHelper.ErrorMsg("系统提示", "清先选择房间再进行操作！", EditWindow.ClientID);
                return;
            }
            //房间没有限制押金，从默认配置取
            if (room.Deposit == 0)
            {
                XmlHelper xmlHelper = new XmlHelper(Server.MapPath("~/Helper/site.xml"));
                room.Deposit = Convert.ToInt32(xmlHelper.Read("/Root/Deposit", ""));
            }
            txtDeposit.Text = room.Deposit.ToString();
            int days = Convert.ToInt32(txtDays.Text);
            double price = room.Price > 0 ? room.Price : room.ClassPrice;
            double reserve = room.Reserve > 0 ? room.Reserve : room.ClassReserve;
            float discount = (float)u.Discount / 100;
            double finalPrice = (int)discount * price; //最终打折价格
            if (finalPrice < reserve)
            {
                finalPrice = reserve;
            }

            txtTotalPrice.Text = txtIsDisCount.Checked ? (finalPrice * days).ToString() : (price * days).ToString();
        }

        protected void SetEditWindow(VOrder tt)
        {

            TCard t = new TCard() { BuildNo = "1", CardNo = "1", EndDate = "201111041200", FloorNo = "1", Memo = "", Port = 1, RoomNo = "0503" };
            int readInfo;
            Card.ReadCard(t, out readInfo);
            if (t == null)
            {
                ExtHelper.GetNotification("系统提示", Card.ErrMessage(readInfo) + "请先扫描房卡再进行入住登记！");
                return;
            }

            //tt.Deposit = tt.Deposit == 0 ? tt.RoomDeposit : tt.Deposit;
            //int totalPrice = tt.IsDisCount ? tt.TotalPrice : tt.RoomPrice;

            //新增入住
            if (tt.Deposit == 0)
            {
                //TRoom room = (TRoom.entityID == tt.RoomID).ListFirst<TRoom>();
                //tt.Deposit = room.Deposit;
                ////没设置该房间的押金，就从系统配置中取
                //if (tt.Deposit == 0)
                //{
                    XmlHelper xmlHelper = new XmlHelper(Server.MapPath("~/Helper/site.xml"));
                    tt.Deposit = Convert.ToInt32(xmlHelper.Read("/Root/Deposit", ""));
                //}
            }
            DateTime endDate = DateTime.ParseExact(t.EndDate + "00", "yyyyMMddHHmmss", System.Globalization.CultureInfo.InvariantCulture);
            txtCardNo.Text = t.CardNo;
            txtEndDate.Text = endDate.ToString();

            hdnDeposit.Text = tt.Deposit.ToString();
            txtID.Text = tt.EntityID.ToString();
            txtDeposit.Text = tt.Deposit.ToString();
			txtDays.Text = tt.Days.ToString();
            //txtTotalPrice.Text = tt.TotalPrice.ToString();
            txtRoomID.SetValue(tt.RoomID.ToString(), tt.RoomClassName + " - " + tt.RoomNO);
			txtStatus.SetValue(tt.Status);
			txtCheckInDate.Text = tt.CheckInDate.ToString();
            //txtIsDisCount.Checked = tt.IsDisCount;
        }

        protected void SaveEditWindow(object sender, DirectEventArgs e)
        {
            using (IConnectinContext cc = DBContext.Context1)
            {
                TOrder tt = Convert.ToInt32(txtID.Text) > 0 ?
                    (TOrder.entityID == Convert.ToInt32(txtID.Text)).ListFirst<TOrder>() : new TOrder();

                tt.Deposit = Convert.ToInt32(txtDeposit.Text);
                tt.Days = Convert.ToInt32(txtDays.Text);
                //tt.TotalPrice = Convert.ToInt32(txtTotalPrice.Text);
                tt.RoomID = Convert.ToInt32(txtRoomID.Value);
                tt.Status = Convert.ToInt32(txtStatus.Value);
                tt.CheckInDate = DateTime.Now;
                tt.CardNO = txtCardNo.Text;

                //修改房间状态
                switch (tt.Status)
                {
                    //case 0:
                    case 1:
                    case 2:
                        (TRoom.entityID == tt.RoomID).Edit<TRoom>(d => { d.Status = tt.Status; }); break;
                    case 3:
                        (TRoom.entityID == tt.RoomID).Edit<TRoom>(d => { d.Status = 1; }); break;
                }


                DBContext.Save(tt);
            }
            Store1.DataBind();
            Store1.Dispose();
            EditWindow.Hide();
        }

        protected void GetExamplesNodes(object sender, NodeLoadEventArgs e)
        {
            if (e.NodeID == "root")
            {
                IList<TRoomClass> ClassList = new Expression().List<TRoomClass>();
                if (ClassList.Count > 0)
                {
                    IList<TRoomClass> Parent = ClassList.AsQueryable().Where(a => a.Pid == 0).ToList(); //父节点
                    IList<TRoom> roomList = new Expression().List<TRoom>();
                    e.Nodes = CreateClassTree(roomList, Parent);
                }
            }
        }

        private TreeNodeCollection CreateClassTree(IList<TRoom> list, IList<TRoomClass> Parent)
        {
            TreeNodeCollection nodes = new TreeNodeCollection(false);
            foreach (TRoomClass t in Parent)
            {
                TreeNode node = new TreeNode();
                node.Icon = Icon.Report;
                IList<TRoom> child = list.AsQueryable().Where(a => a.Cid == t.EntityID && a.Status > 0).ToList();
                if (child.Count > 0)
                {
                    node.NodeID = t.EntityID.ToString();
                    node.Text = t.NameCN;
                    node.SingleClickExpand = true;
                    node.Nodes.AddRange(CreateRoomTree(child));
                    nodes.Add(node);
                }
            }
            return nodes;
        }
        private TreeNodeCollection CreateRoomTree(IList<TRoom> list)
        {
            TreeNodeCollection nodes = new TreeNodeCollection(false);
            foreach (TRoom t in list)
            {
                TreeNode node = new TreeNode();
                node.NodeID = t.EntityID.ToString();
                node.Text = t.RoomNO;
                node.Leaf = true;
                nodes.Add(node);
            }
            return nodes;
        }
    }
}